import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-09-30
 * Time: 12:39
 */

//
class MyTimerTask1 implements Comparable<MyTimerTask1>{
    private long time;
    private Runnable runnable;

    public MyTimerTask1(Runnable runnable, long delay) {
        this.runnable = runnable;
        time = System.currentTimeMillis() + delay;
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask1 o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer1 {
    private PriorityQueue<MyTimerTask1> queue = new PriorityQueue();
    public Object locker = new Object();
    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask1 task1 = new MyTimerTask1(runnable, delay);
            queue.offer(task1);
            locker.notify();
        }
    }
    public MyTimer1() {
        Thread t = new Thread(()-> {
            while(true) {
                try {
                    synchronized (locker) {
                        while(queue.isEmpty()) {
                            locker.wait();
                        }
                        long curTime = System.currentTimeMillis();
                        MyTimerTask1 task1 = queue.peek();
                        if(curTime >= task1.getTime()) {
                            queue.poll();
                            task1.getRunnable().run();
                        } else {
                            locker.wait(task1.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class practice {
    public static void main(String[] args) {
        MyTimer1 myTimer1 = new MyTimer1();
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3");
            }
        },3000);

        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2");
            }
        },2000);

        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1");
            }
        },1000);
        System.out.println("开始运行");
    }
}
